<template>
  <div class="user-edit">
    <div class="top">
      <div class="blue"></div>
      编辑服务信息
    </div>
    <!-- 编辑表单 -->
    <div class="frombox">
      <el-form :model="user" label-width="120px" ref="editRef">
      <el-row>
        <!-- 用户名 -->
        <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
          <el-form-item label="用户名">
            <el-input v-model="user.username" />
          </el-form-item>

          <!-- 密码 -->
        </el-col>
        <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
          <el-form-item label="密码">
            <el-input v-model="user.password" />
          </el-form-item>

          <!-- 昵称 -->
        </el-col>
        <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
          <el-form-item label="昵称">
            <el-input v-model="user.nickname" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <!-- 电话 -->
        <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
          <el-form-item label="电话">
            <el-input v-model="user.phone" />
          </el-form-item>
        </el-col>

        <!-- 性别 -->
        <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
          <el-form-item label="性别">
            <el-radio-group v-model="user.sex">
              <el-radio label="男" />
              <el-radio label="女" />
            </el-radio-group>
          </el-form-item>
        </el-col>

        <!-- 出生日期 -->
        <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
          <el-form-item label="出生日期">
            <el-date-picker
              v-model="user.birthday"
              type="date"
              placeholder="请选择出生日期"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
          <el-form-item label="头像" >
            <el-upload
              class="avatar-uploader"
              action="http://quanzhan.site:5945/api/v1/admin/files"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
          <el-form-item>
            <el-button type="primary" @click="handleSave">保存</el-button>
            <el-button>取消</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    </div>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { addUser, findUsersById, updateUser } from '@/api/user'
export default {
  name: 'UserEdit',
  data() {
    return {
      user: { // 表单填写用户信息
        id: '',
        username: '',
        password: '',
        nickname: '',
        sex: '',
        birthday: '',
        phone: '',
        avatarUrl: '',
      },
      imageUrl: '', // 头像上传成功后的预览图片路径
    }
  },
  computed: {
    /**
     * 上传文件的请求头信息，需要添加 token 认证字段
     */
    headers() {
      return {
        Authorization: 'Bearer ' + this.$store.getters.token,
      }
    },

    rules() {
      // console.log('user.id:', this.user.id)
      return { // 表单校验规则
        username: [
          {required: true, message: '用户名必填!'},
        ],
        password: [
          {required: !this.user.id, message: '密码必填!'},
          {min: 6, message: '最小长度为6位!'}
        ],
      }
    },
  },
  components: {
    Plus,
  },
  async created() {
    // 获取导航中传递的 query 参数
    const { id } = this.$route.query
    if (!id) {
      return
    }
    // 根据 id 查询会员详情
    const result = await findUsersById(id)
    // console.log('会员信息:', result)
    // 根据查询结果回显表单
    this.user = result
    this.imageUrl = result.avatarUrl ? 'http://quanzhan.site:5945/' + result.avatarUrl : ''
  },
  methods: {
    /**
     * 保存表单内容
     */
    handleSave() {
      // 提交数据前，校验表单内容
      this.$refs.editRef.validate(async (isValid, invalidFields) => {
        // console.log('isValid:', isValid)
        // console.log('invalid:', invalidFields)
        // console.log('表单数据:', this.user)
        try {
          if (isValid) { // 通过表单校验，发送网络请求，添加会员
            // 区分当前页面是新增还是修改
            if (this.user.id) { // 有会员的 id，则修改，没有 id 则新增
              await updateUser(this.user)
            } else {
              await addUser(this.user)
            }
            ElMessage.success('保存成功')
            this.$router.push('waite-service')
          }
        } catch (error) {
          ElMessage.error('保存失败:' + error.message)
        }
      })
    },

    /**
     * 文件上传前的处理: 文件格式及大小处理
     */
    beforeAvatarUpload(rawFile) {
      if (rawFile.type !== 'image/jpeg') { // 格式
        ElMessage.error('只能上传jpg格式的图片!')
        return false
      }
      if (rawFile.size / 1024 / 1024 > 2) { // 大小
        ElMessage.error('文件大小不能超过2MB!')
        return false
      }
      return true
    },

    /**
     * 文件上传成功，返回上传文件路径，设置图片预览
     */
    handleAvatarSuccess(response, uploadFile) {
      // console.log('response:', response)
      this.user.avatarUrl = response.data.file
      this.imageUrl = URL.createObjectURL(uploadFile.raw)
    }
  },
}
</script>

<style>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
